<?php
	include_once('db/config.php');

	class UserCartItem
	{
		public $productCode;
		public $userId;
		public $quantity;
		public $dateAdded;
		
		public function __contruct()
		{
			$this->productCode = 0;
			$this->userId = 0;
			$this->quantity = 1;
		}
		
		public function setItem($productCode=0,$userId=0,$quantity=1)
		{
			$this->productCode = $productCode;
			$this->userId = $userId;
			$this->quantity = $quantity;
			
		}
		
		public function addItem()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				$queryString = "call sp_addItemToCart(".mysqli_real_escape_string($dbLink,$this->productCode).",".mysqli_real_escape_string($dbLink,$this->userId).",".mysqli_real_escape_string($dbLink,$this->quantity).")";
				//echo $queryString;exit();
				$resultPointer = mysqli_query($dbLink,$queryString);
				//echo $resultPointer;
				if($resultPointer)
				{
					return true;
				}
				else
				{
					$errorCode = mysqli_errno($dbLink);
					//echo $errorCode;exit();
					if($errorCode!=0)
					{	
						$this->parseDatabaseError($errorCode);
					}
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}
		public function removeItem()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				$queryString = "delete from user_cart where product_code = ".mysqli_real_escape_string($dbLink,$this->productCode)." and user_id = ".mysqli_real_escape_string($dbLink,$this->userId);
				$resultPointer = mysqli_query($dbLink,$queryString);
				if($resultPointer)
				{
					if(mysqli_affected_rows($dbLink)==1)
					{
						return true;
					}
					else
					{
						throw new Exception("Could not remove item because it is not in your cart. ");
					}
					
				}
				else
				{
					$errorCode = mysqli_errno($dbLink);
					echo $errorCode;exit();
					if($errorCode!=0)
					{	
						$this->parseDatabaseError($errorCode);
					}
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}
		
		public function getItem()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				$resultPointer = mysqli_query($dbLink,"call sp_getItemFromUserCart(".mysql_real_escape_string($this->userId).",".mysql_real_escape_string($this->productCode).")");
				if($resultPointer)
				{
					while($resultRow = mysqli_fetch_array($resultPointer))
					{
						return $resultRow;
					}
					return false;
				}
				else
				{
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}

		public function getItemAsProduct()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				
				$resultPointer = mysqli_query($dbLink,"call sp_getProduct(".mysql_real_escape_string($this->productCode).")");
				if($resultPointer)
				{
					while($resultRow = mysqli_fetch_array($resultPointer))
					{
						return $resultRow;
					}
					return false;
				}
				else
				{
					return false;
				}
			}
			catch(Exception $ex)
			{
				return false;
			}
		}
		
		public function getAllItems()
		{
			try
			{	
				connectDb("everythingdb");
				
				global $dbLink;
				
				$resultPointer = mysqli_query($dbLink,"call sp_getAllItemsFromUserCart(".mysqli_real_escape_string($dbLink,$this->userId).")");
				if($resultPointer)
				{	
					$resultTable = array();
					while($resultRow = mysqli_fetch_array($resultPointer))
					{
						array_push($resultTable, $resultRow);
					}
					return $resultTable;
				}
				else
				{
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}
		
		public function updateItem()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				$queryString = "call sp_updateCartQuantity(".mysqli_real_escape_string($dbLink,$this->userId).",".mysqli_real_escape_string($dbLink,$this->productCode).",".mysqli_real_escape_string($dbLink,$this->quantity).")";
				//echo $queryString;exit();
				$resultPointer = mysqli_query($dbLink,$queryString);
				//echo $resultPointer;
				if($resultPointer && (mysqli_affected_rows($dbLink)==1))
				{
					return true;
				}
				else
				{
					$errorCode = mysqli_errno($dbLink);
					//echo $errorCode;exit();
					if($errorCode!=0)
					{	
						$this->parseDatabaseError($errorCode);
					}
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}
		
		public function purchaseItems($creditcardNo)
		{
			$purchaseMessage = '';
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				
				$cartItems = $this->getAllItems();
				if($cartItems)
				{
					$queryError=0;
					connectDb("everythingdb");
					if(mysqli_query($dbLink, "START TRANSACTION"))
					{
						$grandTotal = 0;
						foreach($cartItems as $cartItem)
						{
							$grandTotal += $cartItem['unit_price'];
						}
						
						$queryString = sprintf("insert into invoice (purchase_date,creditcard_no,user_id,total) values (NOW(),'%s',%s,%s)",$creditcardNo,$this->userId,$grandTotal);
						$resultPointer = mysqli_query($dbLink,$queryString);
						//echo $resultPointer;exit();
						if($resultPointer && (mysqli_affected_rows($dbLink)==1))
						{
							$invoiceNumber = mysqli_insert_id($dbLink);
							
							foreach($cartItems as $cartItem)
							{
								if($cartItem['on_hand'] >= $cartItem['quantity'])
								{
									$queryString = sprintf("insert into invoice_item (invoice_no,product_code,quantity) values (%s,%s,%s)",$invoiceNumber,$cartItem['code'],$cartItem['quantity']);
									$resultPointer = mysqli_query($dbLink,$queryString);
									
									if($resultPointer && (mysqli_affected_rows($dbLink)==1))
									{
										$remainingQuantity = $cartItem['on_hand'] - $cartItem['quantity'];
										$queryString = sprintf("update product set on_hand = %s where code = %s",mysqli_real_escape_string($dbLink,$remainingQuantity),mysqli_real_escape_string($dbLink,$cartItem['code']));
										$resultPointer = mysqli_query($dbLink,$queryString);
										if($resultPointer && (mysqli_affected_rows($dbLink)==1))
										{
											$queryString = sprintf("delete from user_cart where product_code = %s and user_id = %s",mysqli_real_escape_string($dbLink,$cartItem['code']),mysqli_real_escape_string($dbLink,$this->userId));
											$resultPointer = mysqli_query($dbLink,$queryString);
	
											if($resultPointer && (mysqli_affected_rows($dbLink)==1))
											{
												
											}
											else
											{
												$queryError++;
												mysqli_query($dbLink, "rollback");
												break;
											}
										}
										else
										{
											$queryError++;
											mysqli_query($dbLink, "rollback");
											break;
										}
									}
									else
									{
										$queryError++;
										mysqli_query($dbLink, "rollback");
										break;
									}
								}
								else
								{
									$queryError++;
									mysqli_query($dbLink, "rollback");
									$purchaseMessage = 'There is not enough "'.$cartItem['name'].'" in stock.';
									return $purchaseMessage;
									break;
								}
							}
							if($queryError==0)
							{
								if(isset($_SESSION['cartCount']))
								{
									$_SESSION['cartCount']=0;
								}
								mysqli_query($dbLink, "commit");
								return true;
							}
							else
							{
								$purchaseMessage = '<span class="failed_msg_span">An error occurred while processing your purchase. Please try again.</span>';
								mysqli_query($dbLink, "rollback");
								return $purchaseMessage;
							}
						}
						else
						{
							$purchaseMessage = '<span class="failed_msg_span">An error occurred while processing your purchase. Please try again.</span>';
							return $purchaseMessage;					
						}
					}
					else
					{
						$purchaseMessage = '<span class="failed_msg_span">An error occurred while starting to process your purchase. Please try again.</span>';
						return $purchaseMessage;	
					}

				}
				else
				{
					$purchaseMessage = '<span class="failed_msg_span">An error occurred while processing your purchase. Please try again.</span>';
					return $purchaseMessage;					
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}
		}
		
		public function countCartItems()
		{
			try
			{
				connectDb("everythingdb");
				global $dbLink;
				$queryString = "select count(*) as user_items_count from user_cart where user_id = ".mysqli_real_escape_string($dbLink,$this->userId);
				//echo $queryString;exit();
				$resultPointer = mysqli_query($dbLink,$queryString);
				//echo $resultPointer;
				if($resultPointer)
				{
					$resultRow = mysqli_fetch_assoc($resultPointer);
					return $resultRow['user_items_count'];
				}
				else
				{
					return false;
				}
			}
			catch(Exception $ex)
			{
				throw new Exception($ex->getMessage());
			}	
		}
		
		public function parseDatabaseError($errorCode)
		{
			switch($errorCode)
			{
				case 1032:
					throw new Exception("Item cannot be found. ");
				break;
				case 1452:
					throw new Exception("This product does not exist.");
				break;
				case 1062:
					$productDetail = $this->getItemAsProduct();
					if($productDetail)
					{
						throw new Exception('<strong>'.$productDetail['name'].'</strong> is already in your cart.');
					}
					else
					{
						throw new Exception(" This product is already in your cart.");
					}
				break;
			}
		}
	}

?>